package com.thghh.ch5.bst;

import com.thghh.ch5.huffman.Traverse;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2020/10/21 10:52
 */
public class TreeMapEntryTraverse<K, V> implements Map.Entry<K, V>, Traverse<V> {

    private Map.Entry<K, V> entry;
    private Class<?> clazz;
    private Field leftField;
    private Field rightField;

    public TreeMapEntryTraverse(Map.Entry<K, V> entry) throws Exception {
        this.entry = entry;
        this.clazz = entry.getClass();
        leftField = clazz.getDeclaredField("left");
        leftField.setAccessible(true);
        rightField = clazz.getDeclaredField("right");
        rightField.setAccessible(true);
    }

    @Override
    public Traverse getLeft() {
        try {
            Map.Entry<K, V> val = (Map.Entry) leftField.get(entry);
            if (val != null) {
                return new TreeMapEntryTraverse(val);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Traverse getRight() {
        try {
            Map.Entry<K, V> val = (Map.Entry) rightField.get(entry);
            if (val != null) {
                return new TreeMapEntryTraverse(val);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public K getKey() {
        return entry.getKey();
    }

    @Override
    public V getValue() {
        return entry.getValue();
    }

    @Override
    public V setValue(V value) {
        return null;
    }

    @Override
    public Traverse getObject() {
        return this;
    }

    @Override
    public String toString() {
        return entry.toString();
    }
}
